<template>
  <div class="app-container">
    <el-row>
      <el-col :span="5" class="user-list">
        <Conversation
          :userid="my_user_id"
          :type="0"
          :userList="userList"
          @handle-command="onHandleCommand"
          @click-item="onSelectUser"
        />
      </el-col>
      <el-col :span="14" class="user-chat">
        <div class="messages-list">
          <el-scrollbar
            style="height: 50vh; overflow-x: hidden"
            ref="scrollbarMsgList"
          >
            <MsgItem
              v-for="(item, index) in messageList"
              :key="index"
              :information="item"
            />
            <UpmsgItem
              v-for="(item, index) in messageListUping"
              :key="index"
              :avatar="myuseUserStore.user.avatar"
              :item="item"
            />
          </el-scrollbar>
        </div>
        <div style="height: 40vh; overflow: hidden">
          <div v-if="group_id > 0">
            <div class="fun-icon">
              <div class="fun-icon-item">
                <div
                  class="el-upload el-upload--picture-card"
                  @click.stop="emojiShow = true"
                >
                  <el-icon class="single-upload__add-btn">
                    <PictureRounded />
                  </el-icon>
                </div>
              </div>
              <div class="fun-icon-item">
                <SingleImage
                  v-model="imgUrl"
                  @up-ing="sendMessageIng"
                  @up-success="sendImgMessage"
                />
              </div>
            </div>
            <div>
              <Emoji v-if="emojiShow" @click-emoji="clickEmoji" />
              <el-input
                v-else
                type="textarea"
                :rows="11"
                @keyup="handleCtrlEnter"
                v-model="message"
                placeholder="请输入内容"
              />
            </div>
            <div class="btn-bottom">
              <div class="btn-bottom-tip">按Enter发送 Ctrl+Enter进行换行</div>
              <div class="btn-bottom-send">
                <el-button type="primary" size="small" @click="sendTextMessage">
                  发送
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="5" class="menubar-info">
        <UserInfo :menubar="memberInfo" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useUserStore } from "@/store";
import socket, { GroupItem, MessageItem } from "@/utils/socket";
import UserAPI from "@/api/user";
import MemberAPI, { type MemberInfo } from "@/api/system/member.api";
// WebSocket 相关状态
const message = ref("");
import SingleImage from "./components/singleImage.vue";
import Conversation from "./components/conversation.vue";
import MsgItem from "./components/msgitem.vue";
import Emoji from "./components/emoji.vue";
import UpmsgItem from "./components/upmsgItem.vue";
import UserInfo from "./components/userinfo.vue";
const myuseUserStore = useUserStore();
const group_id = ref(0);
const my_user_id = ref("");
const admin_id = ref(0);
const messageList = ref([]);
const messageListUping = ref<MessageItem[]>([]);
const userList = ref<GroupItem[]>([]);
const scrollbarMsgList = ref();
const messageOldLen = ref(0);
const emojiShow = ref(false);
const imgUrl = ref("");
const memberInfo = ref<MemberInfo>();

const onHandleCommand = (item: any) => {
  console.log(item);
};
const clickEmoji = (item: any) => {
  console.log(item);
  emojiShow.value = false;
  message.value += item;
};
const handleCtrlEnter = (e: any) => {
  console.log(e);
  if (e.ctrlKey && e.keyCode == 13) {
    console.log("ctrl+enter");
    message.value += "\r";
    return false;
  } else if (e.keyCode == 13) {
    // message.value = message.value.replace(/\r+$/, "");
    console.log("enter");
    sendTextMessage();
  }
};

const onSelectUser = (item: any) => {
  group_id.value = item.id;
  admin_id.value = item.admin_id;
  my_user_id.value = item.user_id;
  getMemberInfo(my_user_id.value);
  GetMessageList();
};

const getMemberInfo = (user_id: any) => {
  let data = {
    user_id: user_id,
  };
  MemberAPI.getInfo(data).then((res: any) => {
    if (res.user) {
      memberInfo.value = res.user;
      console.log(memberInfo.value);
    }
  });
};

//  获取群组列表
const GetGoupList = () => {
  let data = {
    type: "group",
    user_type: "admin",
    group_id: group_id.value + "",
    user_id: admin_id.value + "",
  };
  message.value = JSON.stringify(data);
  socket.send(JSON.parse(message.value));
};

// 标记已读
const ReadMessage = () => {
  console.log("标记已读");
  if (group_id.value > 0) {
    let data = {
      type: "read",
      user_type: "admin",
      group_id: group_id.value + "",
      user_id: admin_id.value + "",
    };
    message.value = JSON.stringify(data);
    socket.send(JSON.parse(message.value));
    message.value = "";
  }
};

const GetMessageList = () => {
  let data = {
    group_id: group_id.value + "",
    page: 1,
    pageSize: 30,
  };
  UserAPI.getChatHistory(data).then((res: any) => {
    if (res.list.length > 0) {
      myuseUserStore.chatData.userMessages[group_id.value] = res.list.reverse();
      console.log("myuseUserStore", myuseUserStore.chatData.userMessages);
    }
    GetGoupList();
  });
};

//滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    nextTick(() => {
      const wrapElement = (
        scrollbarMsgList.value?.$el as HTMLElement
      )?.querySelector(".el-scrollbar__wrap") as HTMLElement | null;
      if (wrapElement) {
        if (messageOldLen.value !== messageList.value.length) {
          messageOldLen.value = messageList.value.length;
          console.log("已经滚动到底部", "");
          ReadMessage();
        }
        wrapElement.scrollTop = wrapElement.scrollHeight;
      }
    });
  }, 500);
};

const sendTextMessage = () => {
  let sendData = {
    type: "text",
    user_type: "admin",
    group_id: group_id.value + "",
    user_id: admin_id.value + "",
    content: message.value,
  };
  if (socket.socket_open) {
    console.log("发送", JSON.stringify(sendData));
    socket.send(sendData);
    message.value = "";
  } else {
    alert("WebSocket 未连接");
  }
};

//  发送图片视频音频 发送中
const sendMessageIng = (item: any) => {
  // items.forEach((item: { name: string; uid: string; url: string }) => {
  //   const sendData: MessageItem = {
  //     type: "image",
  //     user_type: "admin",
  //     group_id: group_id.value + "",
  //     user_id: admin_id.value + "",
  //     content: item.url,
  //     uid: item.uid,
  //   };
  //   messageListUping.value.push(sendData);
  // });
  // scrollToBottom();
  const sendData: MessageItem = {
    type: item.type,
    user_type: "admin",
    group_id: group_id.value + "",
    user_id: admin_id.value + "",
    content: item.url,
    uid: item.uid + "",
  };
  console.log("sendMessageIng", JSON.stringify(sendData));
  messageListUping.value.push(sendData);
  scrollToBottom();
};
const sendImgMessage = (item: any) => {
  let sendData = {
    type: item.type,
    user_type: "admin",
    group_id: group_id.value + "",
    user_id: admin_id.value + "",
    content: item.url,
  };
  if (socket.socket_open) {
    socket.send(sendData);
    messageListUping.value = messageListUping.value.filter(
      (itemx: any) => itemx.uid != item.uid
    );
    message.value = "";
    imgUrl.value = "";
  } else {
    alert("WebSocket 未连接");
  }
};

watch(
  [
    () => myuseUserStore.chatData.chatGroups,
    () => myuseUserStore.chatData.userMessages,
  ],
  ([newChatGroups, newUserMessages]) => {
    if (newChatGroups && newChatGroups != userList.value) {
      userList.value = newChatGroups;
      console.log("newChatGroups", newChatGroups);
    }
    if (newUserMessages && newUserMessages != messageList.value) {
      console.log("newUserMessages", newUserMessages);
      messageList.value = newUserMessages[group_id.value] || [];
      scrollToBottom();
    }
    // if (newMessageList && newMessageList.value !== tempMessageList.value) {
    //   console.log("newMessageList", newMessageList.value);
    //   tempMessageList.value = newMessageList.value;
    //   // ReadMessage();
    // }
  }
);

onMounted(() => {
  userList.value = myuseUserStore.chatData.chatGroups;
});

onBeforeUnmount(() => {});
</script>

<style scoped>
.app-container {
  min-width: 1600px;
}
.user-list {
  background-color: #f5f5f5;
  padding: 5px 10px;
}
.chat-list {
  background-color: #f5f5f5;
}
.menubar-info {
  background-color: #dde9f1;
  padding: 10px 2px;
}
:deep(.el-upload--picture-card) {
  /*  width: var(--el-upload-picture-card-size);
  height: var(--el-upload-picture-card-size); */
  width: 50px;
  height: 50px;
}

.fun-icon {
  width: 100%;
  margin-bottom: 15px;
}

.fun-icon-item {
  margin-right: 10px;
  width: fit-content;
  display: inline-block;
}
</style>
